import 'package:bot_toast/bot_toast.dart';
import 'package:easy_read_comic/controller/app_controller.dart';
import 'package:dio/dio.dart';
import 'package:easy_read_comic/internal/middleware/http_limiting_middleware.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart' as G;
import 'package:logger/logger.dart';

class HttpClient {
  static final BaseOptions baseOptions = BaseOptions(
    baseUrl: "https://8.137.84.0",
    connectTimeout: Duration(seconds: 5),
    receiveTimeout: Duration(seconds: 3),
  );

  final Dio dio = Dio(baseOptions);

  HttpClient() {
    //请求拦截器

    dio.interceptors.add(HttpLimitingMiddleware());

    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (request, handle) {
          if (AppController().IsLoginState) {
            request.headers["Token"] = AppController().Token;
          }
          return handle.next(request);
        },
        onResponse: (response, handle) {
          if (response.data["code"] == 0) {
            if (kDebugMode) {
              Logger().i(response.data.toString());
            }
            BotToast.showSimpleNotification(title: response.data["msg"]);
            return;
          }
          return handle.next(response);
        },
        onError: (DioException error, handler) {
          if (error.response?.statusCode == 401) {
            G.Get.toNamed('/login_with_register');
          }
          return handler.next(error);
        },
      ),
    );
  }

  Future<Response<T>> get<T>(String path,
      {Map<String, dynamic>? queryParameters, Options? options}) async {
    return await dio.get<T>(
      path,
      queryParameters: queryParameters,
      options: options,
    );
  }

  Future<Response<T>> post<T>(String path, {data, Options? options}) async {
    return await dio.post<T>(path, data: data, options: options);
  }
}
